package com.framework.auth.translator;

import com.alibaba.fastjson.JSON;
import com.framework.common.constant.ErrorCode;
import com.framework.common.domain.ResultData;
import com.framework.common.util.StringUtils;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ResultGeneral {
    protected void outputResult(HttpServletResponse response, Exception exception) throws IOException {
        String message = exception.getMessage();
        if (exception instanceof InvalidBearerTokenException) {
            message = "Bearer token 已过期";
        }
        if (exception instanceof OAuth2AuthenticationException) {
            if (StringUtils.isBlank(message)) {
                message = "权限不足";
            }
        }
        if (StringUtils.isBlank(message)) {
            message = "系统错误";
        }

        ResultData resultData = ResultData.error(ErrorCode.Common.invalidToken.getCode(), message);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSON.toJSONString(resultData).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
